import React, { useEffect, useState } from "react";
import axios from "axios";
import "./DailyNews.css"; // 👈 样式文件
import Navbar from './components/Navbar';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
const DailyNews = () => {
  const [articles, setArticles] = useState([]);
  const [selectedDate, setSelectedDate] = useState(new Date());

  const handleDateChange = (date) => {
    setSelectedDate(date);
    fetchNews(date);
  };
  const fetchNews=(date) =>{
    const dateStr = date.toISOString().split('T')[0]; // yyyy-MM-dd
    axios
    .get("http://localhost:8080/consult/getDailyNews", {
      params: {
        date:dateStr
      },
      header:{
        'Authorization':  localStorage.getItem('token'),  // 示例：添加 Bearer token 作为认证头部
        'Content-Type': 'application/json'
      }
    })
    .then((res) => {
      console.log(res.data);
      console.log("数据类型："+typeof res.data);
      setArticles(res.data);
    })
    .catch((err) => {
      console.error("获取新闻失败:", err);
    });
  }
  useEffect(() => {
   fetchNews(selectedDate)
  }, []);

  return (
    <div>
      <Navbar />
      <div style={{ padding: '20px'}}>
        <DatePicker
          selected={selectedDate}
          onChange={handleDateChange}
          dateFormat="yyyy-MM-dd"
          placeholderText="点击选择日期"
          maxDate={new Date()}
        />
      </div>
    <div className="news-list">
      {articles.map((article, idx) => (
        <div key={idx} className="news-card">
          {article.pic && (
            <img src={article.pic} alt="news" className="news-img" />
          )}
          <div className="news-content">
            <h3>{article.title}</h3>
            <div className="news-footer">
              <span>{article.time}</span>
              <a href={article.url} target="_blank" rel="noreferrer">
                阅读原文
              </a>
            </div>
          </div>
        </div>
      ))}
    </div>
  </div>
  );
};

export default DailyNews;